package com.marketing.tenant.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.marketing.common.Result;
import com.marketing.tenant.annotation.RequirePermission;
import com.marketing.tenant.entity.SubscriptionPlan;
import com.marketing.tenant.service.SubscriptionPlanService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * 订阅计划管理控制器
 * 
 * @author Marketing System
 * @since 2024-09-25
 */
@RestController
@RequestMapping("/api/subscription-plans")
@Validated
@Tag(name = "订阅计划管理", description = "订阅计划的增删改查和管理操作")
public class SubscriptionPlanController {
    
    private static final Logger log = LoggerFactory.getLogger(SubscriptionPlanController.class);
    
    @Autowired
    private SubscriptionPlanService subscriptionPlanService;
    
    @PostMapping
    @Operation(summary = "创建订阅计划", description = "创建新的订阅计划")
    @RequirePermission("subscription:plan:create")
    public Result<SubscriptionPlan> createPlan(@Valid @RequestBody SubscriptionPlan plan) {
        try {
            boolean success = subscriptionPlanService.createPlan(plan);
            if (success) {
                return Result.success(plan, "订阅计划创建成功");
            } else {
                return Result.error("订阅计划创建失败");
            }
        } catch (Exception e) {
            log.error("创建订阅计划失败: {}", e.getMessage(), e);
            return Result.error("创建订阅计划失败: " + e.getMessage());
        }
    }
    
    @PutMapping("/{planId}")
    @Operation(summary = "更新订阅计划", description = "更新指定的订阅计划")
    @RequirePermission("subscription:plan:update")
    public Result<SubscriptionPlan> updatePlan(
            @Parameter(description = "计划ID") @PathVariable @NotNull @Min(1) Long planId,
            @Valid @RequestBody SubscriptionPlan plan) {
        try {
            plan.setId(planId);
            boolean success = subscriptionPlanService.updatePlan(plan);
            if (success) {
                return Result.success(plan, "订阅计划更新成功");
            } else {
                return Result.error("订阅计划更新失败");
            }
        } catch (Exception e) {
            log.error("更新订阅计划失败: {}", e.getMessage(), e);
            return Result.error("更新订阅计划失败: " + e.getMessage());
        }
    }
    
    @DeleteMapping("/{planId}")
    @Operation(summary = "删除订阅计划", description = "软删除指定的订阅计划")
    @RequirePermission("subscription:plan:delete")
    public Result<String> deletePlan(
            @Parameter(description = "计划ID") @PathVariable @NotNull @Min(1) Long planId) {
        try {
            boolean success = subscriptionPlanService.deletePlan(planId);
            if (success) {
                return Result.success("订阅计划删除成功");
            } else {
                return Result.error("订阅计划删除失败");
            }
        } catch (Exception e) {
            log.error("删除订阅计划失败: {}", e.getMessage(), e);
            return Result.error("删除订阅计划失败: " + e.getMessage());
        }
    }
    
    @GetMapping("/{planId}")
    @Operation(summary = "获取订阅计划详情", description = "根据ID获取订阅计划详细信息")
    @RequirePermission("subscription:plan:read")
    public Result<SubscriptionPlan> getPlan(
            @Parameter(description = "计划ID") @PathVariable @NotNull @Min(1) Long planId) {
        try {
            SubscriptionPlan plan = subscriptionPlanService.getPlanById(planId);
            if (plan != null) {
                return Result.success(plan, "获取订阅计划成功");
            } else {
                return Result.error("订阅计划不存在");
            }
        } catch (Exception e) {
            log.error("获取订阅计划失败: {}", e.getMessage(), e);
            return Result.error("获取订阅计划失败: " + e.getMessage());
        }
    }
    
    @GetMapping("/name/{planName}")
    @Operation(summary = "根据名称获取订阅计划", description = "根据计划名称获取订阅计划")
    @RequirePermission("subscription:plan:read")
    public Result<SubscriptionPlan> getPlanByName(
            @Parameter(description = "计划名称") @PathVariable String planName) {
        try {
            SubscriptionPlan plan = subscriptionPlanService.getPlanByName(planName);
            if (plan != null) {
                return Result.success(plan, "获取订阅计划成功");
            } else {
                return Result.error("订阅计划不存在");
            }
        } catch (Exception e) {
            log.error("根据名称获取订阅计划失败: {}", e.getMessage(), e);
            return Result.error("获取订阅计划失败: " + e.getMessage());
        }
    }
    
    @GetMapping("/active")
    @Operation(summary = "分页查询可用订阅计划", description = "分页查询状态为活跃的订阅计划")
    public Result<IPage<SubscriptionPlan>> getActivePlans(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") @Min(1) Integer page,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") @Min(1) Integer size) {
        try {
            Page<SubscriptionPlan> pageParam = new Page<>(page, size);
            IPage<SubscriptionPlan> result = subscriptionPlanService.getActivePlans(pageParam);
            return Result.success(result, "查询订阅计划成功");
        } catch (Exception e) {
            log.error("分页查询订阅计划失败: {}", e.getMessage(), e);
            return Result.error("查询订阅计划失败: " + e.getMessage());
        }
    }
    
    @GetMapping("/all-active")
    @Operation(summary = "获取所有可用订阅计划", description = "获取所有状态为活跃的订阅计划")
    public Result<List<SubscriptionPlan>> getAllActivePlans() {
        try {
            List<SubscriptionPlan> plans = subscriptionPlanService.getAllActivePlans();
            return Result.success(plans, "获取订阅计划成功");
        } catch (Exception e) {
            log.error("获取所有订阅计划失败: {}", e.getMessage(), e);
            return Result.error("获取订阅计划失败: " + e.getMessage());
        }
    }
    
    @GetMapping("/recommended")
    @Operation(summary = "获取推荐订阅计划", description = "获取标记为推荐的订阅计划")
    public Result<List<SubscriptionPlan>> getRecommendedPlans() {
        try {
            List<SubscriptionPlan> plans = subscriptionPlanService.getRecommendedPlans();
            return Result.success(plans, "获取推荐计划成功");
        } catch (Exception e) {
            log.error("获取推荐计划失败: {}", e.getMessage(), e);
            return Result.error("获取推荐计划失败: " + e.getMessage());
        }
    }
    
    @GetMapping("/price-range")
    @Operation(summary = "按价格范围查询订阅计划", description = "根据价格范围查询订阅计划")
    public Result<List<SubscriptionPlan>> getPlansByPriceRange(
            @Parameter(description = "最低价格") @RequestParam Double minPrice,
            @Parameter(description = "最高价格") @RequestParam Double maxPrice) {
        try {
            List<SubscriptionPlan> plans = subscriptionPlanService.getPlansByPriceRange(minPrice, maxPrice);
            return Result.success(plans, "查询订阅计划成功");
        } catch (Exception e) {
            log.error("按价格范围查询失败: {}", e.getMessage(), e);
            return Result.error("查询订阅计划失败: " + e.getMessage());
        }
    }
    
    @GetMapping("/feature/{feature}")
    @Operation(summary = "按功能查询订阅计划", description = "根据功能模块查询包含该功能的订阅计划")
    public Result<List<SubscriptionPlan>> getPlansByFeature(
            @Parameter(description = "功能名称") @PathVariable String feature) {
        try {
            List<SubscriptionPlan> plans = subscriptionPlanService.getPlansByFeature(feature);
            return Result.success(plans, "查询订阅计划成功");
        } catch (Exception e) {
            log.error("按功能查询失败: {}", e.getMessage(), e);
            return Result.error("查询订阅计划失败: " + e.getMessage());
        }
    }
    
    @PutMapping("/{planId}/enable")
    @Operation(summary = "启用订阅计划", description = "将订阅计划状态设置为启用")
    @RequirePermission("subscription:plan:update")
    public Result<String> enablePlan(
            @Parameter(description = "计划ID") @PathVariable @NotNull @Min(1) Long planId) {
        try {
            boolean success = subscriptionPlanService.enablePlan(planId);
            if (success) {
                return Result.success("订阅计划启用成功");
            } else {
                return Result.error("订阅计划启用失败");
            }
        } catch (Exception e) {
            log.error("启用订阅计划失败: {}", e.getMessage(), e);
            return Result.error("启用订阅计划失败: " + e.getMessage());
        }
    }
    
    @PutMapping("/{planId}/disable")
    @Operation(summary = "禁用订阅计划", description = "将订阅计划状态设置为禁用")
    @RequirePermission("subscription:plan:update")
    public Result<String> disablePlan(
            @Parameter(description = "计划ID") @PathVariable @NotNull @Min(1) Long planId) {
        try {
            boolean success = subscriptionPlanService.disablePlan(planId);
            if (success) {
                return Result.success("订阅计划禁用成功");
            } else {
                return Result.error("订阅计划禁用失败");
            }
        } catch (Exception e) {
            log.error("禁用订阅计划失败: {}", e.getMessage(), e);
            return Result.error("禁用订阅计划失败: " + e.getMessage());
        }
    }
    
    @PutMapping("/{planId}/recommend")
    @Operation(summary = "设置推荐状态", description = "设置订阅计划的推荐状态")
    @RequirePermission("subscription:plan:update")
    public Result<String> setRecommended(
            @Parameter(description = "计划ID") @PathVariable @NotNull @Min(1) Long planId,
            @Parameter(description = "是否推荐") @RequestParam boolean recommended) {
        try {
            boolean success = subscriptionPlanService.setRecommended(planId, recommended);
            if (success) {
                return Result.success("推荐状态设置成功");
            } else {
                return Result.error("推荐状态设置失败");
            }
        } catch (Exception e) {
            log.error("设置推荐状态失败: {}", e.getMessage(), e);
            return Result.error("设置推荐状态失败: " + e.getMessage());
        }
    }
}